﻿using DevExpress.ExpressApp;
using DevExpress.ExpressApp.ApplicationBuilder;
using DevExpress.ExpressApp.Blazor;
using DevExpress.ExpressApp.Security;
using DevExpress.ExpressApp.Security.ClientServer;
using DevExpress.ExpressApp.SystemModule;
using DevExpress.ExpressApp.Xpo;
using HC.XAP.Blazor.Server.Services;
using HC.XAP.FileUpload.Blazor.Server.Services;

namespace HC.XAP.FileUpload.Blazor.Server;

public class FileUploadBlazorApplication : BlazorApplication {
    public FileUploadBlazorApplication() {
        ApplicationName = "HC.XAP.FileUpload";
        CheckCompatibilityType = DevExpress.ExpressApp.CheckCompatibilityType.DatabaseSchema;
        DatabaseVersionMismatch += FileDecodeBlazorApplication_DatabaseVersionMismatch;
    }
    protected override void OnSetupStarted() {
        base.OnSetupStarted();

        //FileSystemData文件系统需要加入这个获取ConnectionString
        IConfiguration configuration = ServiceProvider.GetRequiredService<IConfiguration>();
        if (configuration.GetConnectionString("ConnectionString") != null)
        {
            ConnectionString = configuration.GetConnectionString("ConnectionString");
        }
        else
            ConnectionString = InMemoryDataStoreProvider.ConnectionString;


#if DEBUG
        if (System.Diagnostics.Debugger.IsAttached && CheckCompatibilityType == CheckCompatibilityType.DatabaseSchema) {
            DatabaseUpdateMode = DatabaseUpdateMode.UpdateDatabaseAlways;
        }
#endif
    }
    private void FileDecodeBlazorApplication_DatabaseVersionMismatch(object sender, DatabaseVersionMismatchEventArgs e) {
#if EASYTEST
        e.Updater.Update();
        e.Handled = true;
#else
        if(System.Diagnostics.Debugger.IsAttached) {
            e.Updater.Update();
            e.Handled = true;
        }
        else {
            string message = "The application cannot connect to the specified database, " +
                "because the database doesn't exist, its version is older " +
                "than that of the application or its schema does not match " +
                "the ORM data model structure. To avoid this error, use one " +
                "of the solutions from the https://www.devexpress.com/kb=T367835 KB Article.";

            if(e.CompatibilityError != null && e.CompatibilityError.Exception != null) {
                message += "\r\n\r\nInner exception: " + e.CompatibilityError.Exception.Message;
            }
            throw new InvalidOperationException(message);
        }
#endif
    }


    /// <summary>
    /// FileSystemData文件系统需要加入这个
    /// </summary>
    /// <param name="args"></param>
    protected override void CreateDefaultObjectSpaceProvider(CreateCustomObjectSpaceProviderEventArgs args)
    {

        IXpoDataStoreProvider dataStoreProvider = GetDataStoreProvider(args.ConnectionString, args.Connection);
        args.ObjectSpaceProviders.Add(new XPObjectSpaceProvider(dataStoreProvider, true));
        args.ObjectSpaceProviders.Add(new NonPersistentObjectSpaceProvider(TypesInfo, null));
    }
    /// <summary>
    /// FileSystemData文件系统需要加入这个
    /// </summary>
    /// <param name="connectionString"></param>
    /// <param name="connection"></param>
    /// <returns></returns>
    private IXpoDataStoreProvider GetDataStoreProvider(string connectionString, System.Data.IDbConnection connection)
    {
        XpoDataStoreProviderAccessor accessor = ServiceProvider.GetRequiredService<XpoDataStoreProviderAccessor>();
        lock (accessor)
        {
            if (accessor.DataStoreProvider == null)
            {
                accessor.DataStoreProvider = XPObjectSpaceProvider.GetDataStoreProvider(connectionString, connection, true);
            }
        }
        return accessor.DataStoreProvider;
    }
}
